package com.mapapp.flutter_mapapp.util;

import android.util.Log;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

public class FTPClientFunctions {

    private static final String TAG = "FTPClientFunctions";

    private FTPClient ftpClient = null; // FTP客户端

    public FTPClient getFtpClient() {
        return ftpClient;
    }

    /**
     * 连接到FTP服务器
     *
     * @param host     ftp服务器域名
     * @param username 访问用户名
     * @param password 访问密码
     * @param port     端口
     * @return 是否连接成功
     */
    public boolean ftpConnect(String host, String username, String password, int port) {
        try {
            ftpClient = new FTPClient();
            ftpClient.setConnectTimeout(10 * 1000);
            Log.d(TAG, "connecting to the ftp server " + host + " ：" + port);
            ftpClient.connect(host, port);
            // 根据返回的状态码，判断链接是否建立成功
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                Log.d(TAG, "login to the ftp server");
                boolean status = ftpClient.login(username, password);
                /*
                 * 设置文件传输模式
                 * 避免一些可能会出现的问题，在这里必须要设定文件的传输格式。
                 * 在这里我们使用BINARY_FILE_TYPE来传输文本、图像和压缩文件。
                 */
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                ftpClient.enterLocalPassiveMode();
                return status;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG, "Error: could not connect to host " + host);
        }
        return false;
    }

    /**
     * 断开ftp服务器连接
     *
     * @return 断开结果
     */
    public boolean ftpDisconnect() {
        // 判断空指针
        if (ftpClient == null) {
            return true;
        }

        // 断开ftp服务器连接
        try {
            ftpClient.logout();
            ftpClient.disconnect();
            return true;
        } catch (Exception e) {
            Log.d(TAG, "Error occurred while disconnecting from ftp server.");
        }
        return false;
    }

    /**
     * ftp 文件上传
     *
     * @param srcFilePath 源文件目录
     * @param desFileName 文件名称
     * @return 文件上传结果
     */

    public boolean ftpUpload(String srcFilePath, String desFileName) {
        boolean status = false;
        try {
            File file = new File(srcFilePath, desFileName);
            FileInputStream srcFileStream = new FileInputStream(file);
            status = ftpClient.storeFile(desFileName, srcFileStream);
            Log.d(TAG, "ftpUpload:status " + status);
            srcFileStream.close();
            if (!status) {
                ftpClient.deleteFile(desFileName);
            }
            return status;
        } catch (Exception e) {
            if (!status) {
                try {
                    ftpClient.deleteFile(desFileName);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            e.printStackTrace();
            Log.d(TAG, "ftpUpload: " + e.getLocalizedMessage());
        }
        return status;
    }

    public void ftpUploadList(String photoDir, List<String> pathList, List<String> nameList,
                              String childPhotoDir, List<String> childPathList, List<String> childNameList) {
        try {
            if (pathList == null && childPathList == null) {
                listener.onSuccess();
                return;
            }

            int totalSize = 0;
            if (pathList != null) {
                totalSize += pathList.size();
            }
            if (childPathList != null) {
                totalSize += childPathList.size();
            }

            int parentTotal = 0;

            ftpClient.changeToParentDirectory();

            if (pathList != null) {
                ftpClient.changeToParentDirectory();
                ftpClient.makeDirectory(photoDir);
                boolean changeWorkingDirectory = ftpClient.changeWorkingDirectory("/" + photoDir);
                if (changeWorkingDirectory) {
                    for (int i = 0; i < pathList.size(); i++) {
                        FileInputStream srcFileStream = new FileInputStream(pathList.get(i));
                        boolean status = ftpClient.storeFile(nameList.get(i), srcFileStream);
                        srcFileStream.close();
                        if (!status) {
                            if (listener != null) {
                                listener.onFailed();
                            }
                            return;
                        } else {
                            if (i == totalSize - 1) {
                                if (listener != null) {
                                    listener.onSuccess();
                                }
                            } else {
                                parentTotal++;
                                if (listener != null) {
                                    listener.onProgress(i + 1, totalSize);
                                }
                            }
                        }
                    }
                } else {
                    listener.onFailed();
                    return;
                }
            }

            if (childPathList != null) {
                ftpClient.changeToParentDirectory();
                ftpClient.makeDirectory(childPhotoDir);
                boolean changeWorkingDirectory = ftpClient.changeWorkingDirectory("/" + childPhotoDir);
                if (changeWorkingDirectory) {
                    for (int i = 0; i < childPathList.size(); i++) {
                        FileInputStream srcFileStream = new FileInputStream(childPathList.get(i));
                        boolean status = ftpClient.storeFile(childNameList.get(i), srcFileStream);
                        srcFileStream.close();
                        if (!status) {
                            if (listener != null) {
                                listener.onFailed();
                            }
                            return;
                        } else {
                            if (i + parentTotal == totalSize - 1) {
                                if (listener != null) {
                                    listener.onSuccess();
                                }
                            } else {
                                if (listener != null) {
                                    listener.onProgress(i + parentTotal + 1, totalSize);
                                }
                            }
                        }
                    }
                } else {
                    listener.onFailed();
                    return;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            if (listener != null) {
                listener.onFailed();
            }
        }
    }

    public interface OnUploadPositionListener {
        void onProgress(int position, int total);

        void onSuccess();

        void onFailed();
    }

    private OnUploadPositionListener listener;

    public void setListener(OnUploadPositionListener listener) {
        this.listener = listener;
    }

    /**
     * ftp 更改目录
     *
     * @param path 更改的路径
     * @return 更改是否成功
     */
    public boolean ftpChangeDir(String path) {
        boolean status = false;
        try {
            status = ftpClient.changeWorkingDirectory(path);
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG, "change directory failed: " + e.getLocalizedMessage());
        }
        return status;
    }

}
